<?php
namespace Modules\Region\Entity;

use Core\Mvc\Entity\Adapter\ConfigList as BaseConfigListEntity;
use Phalcon\Di;

class Block extends BaseConfigListEntity
{
    protected $_region;
    protected $_entity = 'block';
    protected $_module = 'region';
    protected $_data;
    protected $_theme;

    public function setRegion(string $region)
    {
        $this->_region = $region;
        return $this;
    }

    public function setTheme($theme)
    {
        $this->_theme = $theme;
        return $this;
    }

    public function getTheme()
    {
        return $this->_theme;
    }

    public function getRegion()
    {
        return $this->_region;
    }

    public function getLinks()
    {
        if (!$this->_links) {
            $this->_links = [
                'edit' => [
                    'href' => [
                        'for' => 'adminRegionBlockEdit',
                        'region' => $this->_region,
                        'theme' => $this->_theme,
                        'block' => $this->getId(),
                    ],
                    'data-target' => 'right_handle',
                    'icon' => 'info',
                    'name' => '编辑',
                ],
                'delete' => [
                    'href' => [
                        'for' => 'adminRegionBlockDelete',
                        'region' => $this->_region,
                        'theme' => $this->_theme,
                        'block' => $this->getId(),
                    ],
                    'data-target' => 'right_handle',
                    'icon' => 'info',
                    'name' => '删除',
                ],
            ];
        }
        return $this->_links;
    }

    public function delete()
    {
        if (!$this->getId()) {
            throw new \Exception('实体对象为空，不用删除');
        }
        $blockDataDelete = false;
        $blockList = $this->config->get('m.region.region' . ucfirst($this->_theme) . ucfirst($this->_region) . 'BlockList');
        $oldBlockList = $blockList;
        unset($blockList[$this->getId()]);
        if ($this->config->set('m.region.region' . ucfirst($this->_theme) . ucfirst($this->_region) . 'BlockList', $blockList)) {
            $blockDataDelete = $this->config->delete('m.region.block' . ucfirst($this->_theme) . ucfirst($this->_region) . ucfirst($this->getId()) . 'Data');
        }
        if ($blockDataDelete) {
            return true;
        } else {
            $this->config->set('m.region.region' . ucfirst($this->_theme) . ucfirst($this->_region) . 'BlockList', $oldBlockList);
        }
        return false;
    }

    public function save()
    {
        $data = $this->_form->getData();
        $blockList = $this->config->get('m.region.region' . ucfirst($this->_theme) . ucfirst($this->_region) . 'BlockList');
        $oldBlockList = $blockList;
        if (isset($data['id'])) {
            $id = $data['id'];
        } else {
            $id = $this->getId();
        }
        $blockList[$id] = $id;
        $saveState = $this->config->set('m.region.region' . ucfirst($this->_theme) . ucfirst($this->_region) . 'BlockList', $blockList);
        $data['region'] = $this->_region;
        $data['theme'] = $this->_theme;
        $data['contentModel'] = $this->contentModel;
        $saveData = $this->config->set('m.region.block' . ucfirst($this->_theme) . ucfirst($this->_region) . ucfirst($id) . 'Data', $data);
        if ($saveState && $saveData) {
            $this->_save = true;
            return $this->_form;
        } else {
            $this->_save = false;
            $this->config->set('m.region.region' . ucfirst($this->_theme) . ucfirst($this->_region) . 'BlockList', $oldBlockList);
            $this->config->delete('m.region.block' . ucfirst($this->_theme) . ucfirst($this->_region) . ucfirst($id) . 'Data');
        }
        return false;
    }

    public function setData($data)
    {
        $this->_data = $data;
        return $this;
    }

    public function getData()
    {
        return $this->_data;
    }

    public function render($noAjax = false)
    {
        $access = [
            'path' => $this->_data['path'],
            'expath' => $this->_data['expath'],
            'roles' => $this->_data['roles'],
            'exroles' => $this->_data['exroles'],
        ];
        if ($this->security->access($access) == false) {
            return '';
        }
        if ($this->_data['loadType'] == 'ajax' && $noAjax == false) {
            return [
                '#templates' => [
                    'blockAjax',
                ],
                '#module' => 'region',
                'data' => [
                    'theme' => $this->_data['theme'],
                    'id' => $this->getId(),
                    'region' => $this->_region,
                    'device' => (isset($this->_data['device']) && $this->_data['device']) ? array_values($this->_data['device']) : false,
                ],
            ];
        }
        $contentModelList = $this->entityManager->contentModel('block');
        if (!isset($contentModelList[$this->contentModel])) {
            return '';
        }
        $contentModelInfo = $contentModelList[$this->contentModel];
        if (isset($contentModelInfo['callable']) && isCallable($contentModelInfo['callable'])) {
            return call_user_func($contentModelInfo['callable'], $this);
        }
        return [
            '#templates' => [
                'block',
                'block-' . $this->contentModel,
                'block-' . $this->getId(),
            ],
            '#module' => 'region',
            'data' => $this,
        ];
    }

    public static function find(array $param = null)
    {
        if (!isset($param['region']) || !isset($param['theme'])) {
            throw new \Exception('参数错误');
        }
        $di = Di::getDefault();
        $configServer = $di->getShared('config');
        $regionNode = $di->getShared('entityManager')->get('region', ['theme' => $param['theme'], 'region' => $param['region']]);
        if (!$regionNode) {
            return false;
        }
        //$blockContentModel = $di->getShared('entityManager')->contentModel('block');
        $data = $configServer->get('m.region.region' . ucfirst($param['theme']) . ucfirst($param['region']) . 'BlockList');
        foreach ($data as $key => $value) {
            $configObject = $di->getShared('entityManager')->get(getClassName(__CLASS__));

            if (!($configObject instanceof Block)) {
                throw new \Exception('不是合法的Block实体');
            }

            $blockData = $configServer->get('m.region.block' . ucfirst($param['theme']) . ucfirst($param['region']) . ucfirst($key) . 'Data');
            $configObject->setId($key);
            $configObject->name = $blockData['name'];
            $configObject->setRegion($blockData['region']);
            $configObject->setTheme($blockData['theme']);
            $configObject->setData($blockData);
            $configObject->setContentModel($blockData['contentModel']);
            foreach ($blockData as $key => $value) {
                $configObject->{$key} = $value;
            }
            //print_r($configObject->getRegion());
            //$configObject->setField($blockContentModel[$blockData['contentModel']]['field']);
            yield $configObject;
        }
    }

    public static function findFirst(array $param = null)
    {
        if (!isset($param['block']) || !isset($param['region']) || !isset($param['theme'])) {
            throw new \Exception('参数错误');
        }
        $di = Di::getDefault();
        $configServer = $di->getShared('config');
        $regionNode = $di->getShared('entityManager')->get('region', ['theme' => $param['theme'], 'region' => $param['region']]);
        //print_r($regionList);
        if (!$regionNode) {
            return false;
        }
        $data = $configServer->get('m.region.region' . ucfirst($param['theme']) . ucfirst($param['region']) . 'BlockList');
        if (!isset($data[$param['block']])) {
            return false;
        }
        $configObject = $di->getShared('entityManager')->get(getClassName(__CLASS__));

        if (!($configObject instanceof Block)) {
            throw new \Exception('不是合法的Block实体');
        }

        $blockData = $configServer->get('m.region.block' . ucfirst($param['theme']) . ucfirst($param['region']) . ucfirst($param['block']) . 'Data');
        $configObject->setData($blockData);
        $configObject->name = $blockData['name'];
        $configObject->setTheme($blockData['theme']);
        $configObject->setRegion($blockData['region']);
        $configObject->setId($param['block']);
        $configObject->setContentModel($blockData['contentModel']);
        foreach ($blockData as $key => $value) {
            $configObject->{$key} = $value;
        }
        //$configObject->setField($blockContentModel[$blockData['contentModel']]['field']);
        return $configObject;
    }
}
